package com.zrf.gulimall.cart.controller;

import com.zrf.gulimall.cart.service.ShopCartService;
import com.zrf.gulimall.cart.vo.CartItemVo;
import com.zrf.gulimall.cart.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * @Author zhanrf
 * @Date 2022/1/2 23:43
 */
@Controller
public class ShopCartController {

	@Autowired
	private ShopCartService shopCartService;

	@GetMapping("/cart.html")
	public String cart(Model model) {
		CartVo cartVo = shopCartService.getCart();
		model.addAttribute("cart",cartVo);
		return "cartList";
	}

	@GetMapping("/addCartItem")
	public String addToCart(@RequestParam("skuId") Long skuId,
							@RequestParam("num") Integer num,
							RedirectAttributes attributes) {
		shopCartService.addCartItem(skuId, num);
		attributes.addAttribute("skuId",skuId);
		return "redirect:http://cart.gulimall.com/addToCartSuccessPage.html";
	}

	/**
	 * 跳转到添加购物车成功页面
	 */
	@GetMapping(value = "/addToCartSuccessPage.html")
	public String addToCartSuccessPage(@RequestParam("skuId") Long skuId,
									   Model model) {
		//重定向到成功页面。再次查询购物车数据即可
		CartItemVo cartItemVo = shopCartService.getCartItem(skuId);
		model.addAttribute("cartItem",cartItemVo);
		return "success";
	}

	/**
	 * 商品是否选中
	 */
	@GetMapping(value = "/checkItem")
	public String checkItem(@RequestParam(value = "skuId") Long skuId,
							@RequestParam(value = "checked") Integer checked) {
		shopCartService.checkItem(skuId,checked);
		return "redirect:http://cart.gulimall.com/cart.html";

	}

	/**
	 * 改变商品数量
	 */
	@GetMapping(value = "/countItem")
	public String countItem(@RequestParam(value = "skuId") Long skuId,
							@RequestParam(value = "num") Integer num) {
		shopCartService.changeItemCount(skuId,num);
		return "redirect:http://cart.gulimall.com/cart.html";
	}

	/**
	 * 删除商品信息
	 */
	@GetMapping(value = "/deleteItem")
	public String deleteItem(@RequestParam("skuId") Integer skuId) {
		shopCartService.deleteIdCartInfo(skuId);
		return "redirect:http://cart.gulimall.com/cart.html";
	}

	/**
	 * 获取当前用户的购物车商品项
	 */
	@GetMapping(value = "/currentUserCartItems")
	@ResponseBody
	public List<CartItemVo> getCurrentCartItems() {
		return shopCartService.getUserCartItems();
	}
}
